package com.ming.config;

import org.springframework.core.io.ClassPathResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import java.security.KeyPair;

/**
 * 1. token的存储
 * 2. jwt的转换器
 * 3. 配置第三方应用
 * 4. 暴露服务端点
 * 5. 加密器
 */
@Configuration
public class AuthorizationConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;


    /**
     * token的存储
     * 需要jwt的转换器
     *
     * @return
     */
//    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    /**
     * JWT token 的转换器
     *
     * @return
     */
//    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        // 直接非对称加密
        ClassPathResource resource = new ClassPathResource("cxs-jwt.jks");
        // 2.根据秘钥 创建钥匙工厂
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(resource, "cxs123".toCharArray());
        // 3.拿到钥匙
        KeyPair keyPair = keyStoreKeyFactory.getKeyPair("cxs-jwt");
        // 4.设置私钥到转换器中
        jwtAccessTokenConverter.setKeyPair(keyPair);
        return jwtAccessTokenConverter;
    }

    /**
     * 配置第三方应用的
     * 就把前台应用当做第三方应用
     *
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("web")
                .secret(passwordEncoder().encode("web-secret"))
                .scopes("all")
                .authorizedGrantTypes("password") // 密码授权
                .accessTokenValiditySeconds(14400) // 四个小时  6个小时  7天
                .redirectUris("https://www.baidu.com")
                .and()
                .withClient("client")
                .secret(passwordEncoder().encode("client-secret"))
                .scopes("read")
                .authorizedGrantTypes("client_credentials") // 客户端授权 一般可以用在系统之间自发远程调用 不是用户驱动的
                .accessTokenValiditySeconds(Integer.MAX_VALUE) // 可以用66年
                .redirectUris("https://www.baidu.com");
    }

    /**
     * 暴露服务给授权中心使用
     *
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore())
                .accessTokenConverter(jwtAccessTokenConverter())
                .authenticationManager(authenticationManager);
    }

    /**
     * 加密器
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    public static void main(String[] args) {
        String encode = new AuthorizationConfig().passwordEncoder().encode("123456");
        System.out.println(encode);
    }
}

